package com.birdpiss.web.manager;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.birdpiss.commons.domain.Account;
import com.birdpiss.commons.domain.AccountType;
import com.birdpiss.commons.domain.Transaction;
import com.birdpiss.commons.domain.TransactionStatus;
import com.birdpiss.commons.manager.interfaces.AccountManager;
import com.birdpiss.commons.manager.interfaces.TransactionManager;
import com.birdpiss.commons.utils.NumberUtils;
import com.birdpiss.web.domain.WebTransaction;
import com.birdpiss.web.manager.interfaces.WebTransactionManager;

/**
 * The Class DefaultWebTransactionManager.
 *
 * @author mark
 */
@Service("webTransactionManager")
public class DefaultWebTransactionManager implements WebTransactionManager {

	private static final Logger log = Logger.getLogger(WebTransactionManager.class);
	private AccountManager accountManager;
	private TransactionManager transactionManager;

	/* (non-Javadoc)
	 * @see com.birdpiss.web.manager.interfaces.WebTransactionManager#processWebTransaction(com.birdpiss.web.domain.WebTransaction)
	 */
	@Override
	public WebTransaction processWebTransaction(WebTransaction webTransaction) {

		webTransaction.getDebitAccount().setAccountType(AccountType.getAccountType(Integer.valueOf(webTransaction.getAccountType())));

		if (log.isDebugEnabled()) log.debug("Processing web transaction - " + webTransaction);

		Account creditAccount = this.accountManager.getAccountByUserId(Integer.valueOf(webTransaction.getCreditUserId()));
		Account debitAccount = this.accountManager.insertAccount(webTransaction.getDebitAccount());
		Transaction transaction = this.transactionManager.insertTransaction(this.getTransaction(debitAccount, creditAccount, webTransaction));

		return webTransaction;
	}

	/**
	 * Gets the transaction.
	 *
	 * @param debitAccount the debit account
	 * @param creditAccount the credit account
	 * @param webTransaction the web transaction
	 *
	 * @return the transaction
	 */
	private Transaction getTransaction(Account debitAccount, Account creditAccount, WebTransaction webTransaction) {
		Transaction transaction = new Transaction();

		transaction.setCreditAccountId(creditAccount.getId());
		transaction.setDebitAccountId(debitAccount.getId());
		transaction.setAmount(NumberUtils.setBigDecimalCurrencyScale(webTransaction.getAmount()));
		transaction.setTransactionStatus(TransactionStatus.PENDING);

		return transaction;
	}

	/**
	 * Sets the account manager.
	 *
	 * @param accountManager the new account manager
	 */
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	/**
	 * Sets the transaction manager.
	 *
	 * @param transactionManager the new transaction manager
	 */
	@Autowired
	public void setTransactionManager(TransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

}
